<!--
  -    Copyright (c) 2018-2025, infomng All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: infomng
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page.sync="page"
        :data="tableData"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load=""
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="handleDel">
        <template slot="menuLeft">
        <!--  <el-button
            v-if="permissions.pfoc_realityproductline_export"
            class="filter-item"
            plain
            type="primary"
            size="small"
            icon="el-icon-download"
            @click="exportExcel">导出
          </el-button>-->
          <el-button type="primary" icon="el-icon-plus" @click="addProduct">添加产品</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button type="text"  icon="el-icon-view"  size="small" plain  @click="handleView(scope.row,scope.index)">产品工艺预览</el-button>
          <el-button type="text"  icon="el-icon-delete"  size="small" plain  @click="handleDel(scope.row,scope.index)">删除</el-button>
        </template>
      </avue-crud>
      <!--新增产品页面-->
      <el-dialog title=""
                 :visible.sync="addProductDialogVisible"
                 width="60%"
                 lock-scroll
                 append-to-body
                 v-if="addProductDialogVisible"
                 :close-on-click-modal="false"
                 :fullscreen="addProductDialogFull">
        <template slot="title">
          <div class="avue-crud__dialog__header">
              <span class="el-dialog__title">
                  <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
                  添加产品
              </span>
          </div>
        </template>
        <el-main>
          <el-form ref="form" :model="form" label-width="140px" :rules="rules">
            <el-form-item label="已发布产品工艺：" prop="releaseId" >
              <el-select v-model="form.releaseId" placeholder="请选择已发布产品工艺"  multiple filterable  style="width:80%;">
                <el-option
                  @click.native="checkProduct(item)"
                  v-for="item in releaseProductList"
                  :key="item.id"
                  :label="`【产品类型：`+item.productLineType + `】【产品工艺：`+item.productProcessName+`】【品号：`+item.articleNumber+`】` "
                  :value="item.id">
                  <span style="color: #5e80a6; font-size: 13px">产品类型：{{ item.productLineType }}</span>
                  <span style="float: left">产品工艺：{{ item.productProcessName }}</span>
                  <span style=" color: #5e80a6; font-size: 13px">品号：{{ item.articleNumber }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <div style="margin-top: 35px;text-align: -webkit-center">
              <el-button type="primary" @click="saveProduct">保存</el-button>
              <el-button @click="closeAddProduct">取消</el-button>
            </div>
          </el-form>
        </el-main>
      </el-dialog>


      <!--预览弹窗页面-->
      <el-dialog title=""
                 :visible.sync="viewDialogVisible"
                 width="50%"
                 lock-scroll
                 append-to-body
                 v-if="viewDialogVisible"
                 :fullscreen="viewDialogFull">
        <el-backtop target=".el-card__body .el-dialog__wrapper .el-dialog" :right="15" :bottom="20" :visibility-height="1" />
        <template slot="title">
          <div class="avue-crud__dialog__header">
              <span class="el-dialog__title">
                  <span style="display:inline-block;background-color: #3478f5;width:3px;height:20px;margin-right:5px; float: left;margin-top:2px"></span>
                  已发布产品工艺流程预览
              </span>
          </div>
        </template>
        <!--预览工艺产线页面-->
        <viewProduct ref="viewCraftRef"  :id="id" :productLineTypeList="productLineTypeList"/>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import { fetchList, addObj, putObj, delObj} from '@/api/pfoc/realityproductline'
import { tableOption } from '@/const/crud/pfoc/realityproductline'
import {getReleaseAndDetailsList} from '@/api/pfoc/productproductionrelease' //获取已发布产品工艺
import {saveRealityLine} from '@/api/pfoc/realityproductline'
import { remote} from '@/api/admin/dict'
import { mapGetters } from 'vuex'
/**引入预览工艺产线页面*/
import viewProduct from '@/views/pfoc/productproductionrelease/view-release'

/**
 * 产品目录管理
 */
export default {
    name: 'product-page',
    components: {
        //预览工艺产线页面
        viewProduct,
    },
    props:{
        lineId:{//产线ID
            type:String
        },
        realityLineName:{//产线名称
            type:String
        },
        lineNodeList:{ //产线工序节点集合（用于判断添加产品是否符合当前产线工序）
            type:Array
        },
        lineArticleNumberStr:{//当前产线下已存在的品号字符串集合
            type:String
        }
    },
    data() {
      return {
        searchForm: {},
        tableData: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        addProductDialogVisible:false,//新增产品页面开关
        addProductDialogFull:false,//新增产品页面弹窗缩放开关（默认放大）
        viewDialogVisible:false,//预览工艺产线页面开关
        viewDialogFull:true,//预览工艺产线页面弹窗缩放开关（默认放大）
        productLineTypeList:[],//产品类型集合
        workshopSectionList:[],//工段集合
        releaseProductList:[],//已发布产品集合
        form:{
            releaseId:[],//已发布产品工艺ID
        },
        rules: {
            releaseId: [
                { type: 'array', required: true, message: '请至少选择一个产品工艺',trigger: ['blur', 'change']}
            ]
        },
        itemCodeStr:"",//产品选择字的品号符串用于判断产线下所选产品品号是否重复
        articleNumberStr:this.lineArticleNumberStr, //避免直接修改父组件传过来的值
      }
    },
    computed: {
      ...mapGetters(['permissions']),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permissions.pfoc_realityproductline_add, false),
          delBtn: this.vaildData(this.permissions.pfoc_realityproductline_del, false),
          editBtn: this.vaildData(this.permissions.pfoc_realityproductline_edit, false)
        }
      }
    },
    mounted() {
        //获取所已发布产品工艺以及详情
        this.getReleaseAndDetailsListData();
        //获取产线类型
        this.getProductLineTypeListData();
        //获取工段
        // this.getWorkshopSectionListData();

    },
    methods: {
      // 列表查询
      getList(page, params) {
        this.searchForm.lineMainId = this.lineId;
        this.tableLoading = true
        fetchList(Object.assign({
          descs:"create_time",
          current: page.currentPage,
          size: page.pageSize
        }, params, this.searchForm)).then(response => {
          this.tableData = response.data.data.records
          this.page.total = response.data.data.total
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      },
      // 删除
      handleDel: function(row, index) {
          this.$confirm('是否确认删除品号为【' + row.articleNumber+'】的产品工艺吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return delObj(row.id)
        }).then(data => {
          this.$message.success('删除成功')
          this.getList(this.page)
          this.$emit('mainRefreshChange');//刷新产线页面
          this.articleNumberStr = this.removeSpecificString( this.articleNumberStr,row.articleNumber).toString();
          this.itemCodeStr = this.removeSpecificString( this.itemCodeStr,row.articleNumber).toString();
        })
      },
      // 更新
      handleUpdate: function(row, index, done, loading) {
        putObj(row).then(data => {
          this.$message.success('修改成功')
          done()
          this.getList(this.page)
        }).catch(() => {
          loading()
        })
      },
      // 保存
      handleSave: function(row, done, loading) {
        addObj(row).then(data => {
          this.$message.success('添加成功')
          done()
          this.getList(this.page)
        }).catch(() => {
          loading()
        })
      },
      // 每页条数改变事件
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
      },
      // 当前页发生改变事件
      currentChange(current) {
        this.page.currentPage = current
      },
      // 查询事件
      searchChange(form, done) {
        this.searchForm = form
        this.page.currentPage = 1
        this.getList(this.page, form)
        done()
      },
      // 刷新事件
      refreshChange() {
        this.getList(this.page)
      },
      //  导出excel
      exportExcel() {
        this.downBlobFile('/pfoc/realityproductline/export', this.searchForm, 'realityproductline.xlsx')
      },
      //新增产品
      addProduct(){
          //每次打开前清空之前所选
          this.form.releaseId =[];
          //打开新增产品页面
          this.addProductDialogVisible = true;
      },
      //关闭新增产品弹窗
      closeAddProduct(){
          //关闭新增产品页面
          this.addProductDialogVisible = false;
          //刷新列表
          this.refreshChange();
          this.$emit('mainRefreshChange');//刷新产线页面
      },

      //获取产线类型
      getProductLineTypeListData(){
          remote("product_line").then(response => {
              this.productLineTypeList=response.data.data;
          })

      },
      //获取工段
      getWorkshopSectionListData(){
          remote("workshop_section").then(response => {
              this.workshopSectionList=response.data.data;
          })
      },
    //获取已发布产品工艺以及详情
     getReleaseAndDetailsListData(){
         getReleaseAndDetailsList().then(response => {
            this.releaseProductList=response.data.data;
        })

    },
    //校验当前选择产品工艺工序是否符合当前产线
    checkProduct(row){
        var flg = false;//产品工艺是否符合标记，默认不符合
        //获取当前选择工艺工序节点集合
        var productNodeList = JSON.parse(row.processNodes);
        // 将 lineNodeList 转换为 Set 以提高查找效率
        var lineProcessSet = new Set(this.lineNodeList);
        for (var i = 0; i < productNodeList.length; i++) {
          const productProcessId = productNodeList[i].mark;
          if (lineProcessSet.has(productProcessId)) {
            flg = true;
            break;
          }else{
            flg = false;
            break;
          }
        }
        if(!flg){
           this.$message.error("当前所选产品工艺工序与当前产品不匹配");
            const index = this.form.releaseId.indexOf(row.id);//获取当前选择选项位置
            if (index !== -1) {
                this.form.releaseId.splice(index, 1);//删除当前选项
            }
        }

        if(this.form.releaseId.includes(row.id)) { //不包含则为取消操作
            if (this.articleNumberStr.includes(row.articleNumber) || this.itemCodeStr.includes(row.articleNumber)) {//产线可生产品号
                this.$message.error("已存在所选产品");
                const index = this.form.releaseId.indexOf(row.id);//获取当前选择选项位置
                if (index !== -1) {
                    this.form.releaseId.splice(index, 1);//删除当前选项
                }
            }
        }



    },
    //保存产品工艺
     saveProduct(){
        this.$refs['form'].validate((valid) => {
            if (valid) {
                var data={
                    lineMainId:this.lineId,//真实产线主表ID
                    realityLineName:this.realityLineName,//产线名称
                    releaseIdArr:this.form.releaseId,//已发布产品id集合
                }
                //提交
               saveRealityLine(data).then(response => {
                    if(response.data.data.length>0) {
                        this.$message.warning(
                            {
                                message: "添加成功，其中产品工艺——品号："+response.data.data+"等与当前真实产线已绑定，已忽略重复添加",
                                duration: 5000 // 设置时长为5秒
                            });
                    }else{
                        this.$message.success("保存成功。")
                    }
                   //判断当前所选品号在当前产线的产品中是否存在
                   var itemArr=[];//所选品号集合
                   for(var n=0;n<this.form.releaseId.length;n++){//遍历所选产品ID
                     for (var m=0; m<this.releaseProductList.length;m++){//遍历所有产品集合
                       if(this.form.releaseId[n]===this.releaseProductList[m].id){//判断所选产品取出品号
                         itemArr.push(this.releaseProductList[m].articleNumber);
                       }
                     }
                   }
                   this.itemCodeStr =  itemArr.toString();
                   this.closeAddProduct();//关闭新增页面
                });
            } else {
                return false;
            }
        });
    },
    //预览
    handleView(row){
        this.articleNumber=row.articleNumber;//品号
        this.craftLineName=row.productProcessName;//工艺产线名称
        this.id = row.releaseId;//已发布工艺产线ID用于预览时查询数据
        //打开预览工艺产线页面
        this.viewDialogVisible = true;
        this.$nextTick(() => {
            //调用预览页面工艺产线查询方法
            this.$refs.viewCraftRef.getProductProductionRelease();
        })
    },
    //从逗号分隔的字符串中删除某个子串的js函数
    removeSpecificString(str, toRemove) {
        return str.split(',').filter(item => item.trim() !== toRemove.trim());
    }
  }
}
</script>
